/**
 * 用户设置页面
 */
import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";
import {
  Table,
  Space,
  Button,
  Tooltip,
  Modal,
  Form,
  Input,
  Select,
  message,
} from "antd";
import { UserSwitchOutlined, KeyOutlined } from "@ant-design/icons";
import { ITStore } from "../../store";
import { ITColumns, ITDictValue, ITUserInfo } from "../../store/interfaces";

type TProp = {
  store: ITStore;
};

interface ITPermissionModalProp extends TProp {
  data: ITUserInfo | null;
  close: () => void;
}

type privateForm = {
  id: string;
  account: string;
  privilege: string;
};

type TPwdForm = {
  account: string;
  password: string;
  confirmpassword: string;
};

const { Option } = Select;

// 修改密码
const PwdModal: FC<ITPermissionModalProp | any> = inject("store")(
  observer(({ store, data, close }: ITPermissionModalProp) => {
    const {
      languageStore: { lang },
      userStore: { changePassword },
    } = store;

    const [form] = Form.useForm();
    const [changeLoading, setChangeLoading] = useState(false);

    const closeModal = () => {
      form.resetFields();
      close();
    };

    const onFinish = async (values: TPwdForm) => {
      const { confirmpassword, password } = values;
      if (confirmpassword !== password) {
        message.error(lang["langpwdnotsame"]);
      } else {
        setChangeLoading(true);
        const res: any = await changePassword({
          password,
          id: data?.id,
        });
        setChangeLoading(false);
        if (!res) {
          message.success(lang["langmodifysuccess"]);
          closeModal();
        } else {
          message.error(lang["langfailmodify"]);
        }
      }
    };

    useEffect(() => {
      form.setFieldsValue({
        account: data?.account,
      });
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data]);

    return (
      <Modal
        forceRender
        title={lang["langmodifypwd"]}
        open={!!data}
        onOk={() => {
          form.submit();
        }}
        onCancel={closeModal}
        destroyOnClose={true}
        confirmLoading={changeLoading}
      >
        <Form
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          form={form}
          onFinish={onFinish}
          style={{ width: "480px", padding: "20px 0 0 20px" }}
        >
          <Form.Item
            label={lang["langaccount"]}
            name="account"
            rules={[{ required: true }]}
          >
            <Input disabled={true} />
          </Form.Item>
          <Form.Item
            label={lang["langpassword"]}
            name="password"
            rules={[{ required: true, min: 6 }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label={lang["langcnfpwd"]}
            name="confirmpassword"
            rules={[{ required: true, min: 6 }]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    );
  })
);

// 修改权限
const PermissionModal: FC<ITPermissionModalProp | any> = inject("store")(
  observer(({ store, data, close }: ITPermissionModalProp) => {
    const {
      languageStore: { lang, langCur },
      dictionaryStore: { getDictValuesByKey },
      userStore: { changePermission, getAllUser },
    } = store;

    const [form] = Form.useForm();

    const [privateOption, setPrivateOption] = useState<ITDictValue[]>([]);

    const [changeLoading, setChangeLoading] = useState(false);

    const closeModal = () => {
      close();
      form.resetFields();
    };

    useEffect(() => {
      setPrivateOption(getDictValuesByKey("userType"));
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    useEffect(() => {
      form.setFieldsValue(data);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data]);

    const onFinish = async (values: privateForm) => {
      const { id, privilege } = values;
      setChangeLoading(true);
      const res: any = await changePermission({ id, privilege });
      setChangeLoading(false);
      if (!res) {
        getAllUser();
        message.success(lang["langdeletesuccess"]);
        closeModal();
      } else {
        message.error(res.msg);
      }
    };

    return (
      <Modal
        forceRender
        title={lang["langchangepermi"]}
        open={!!data}
        onOk={() => {
          form.submit();
        }}
        onCancel={closeModal}
        destroyOnClose={true}
        confirmLoading={changeLoading}
      >
        <Form
          name="changeprivate"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          form={form}
          onFinish={onFinish}
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item
            label={lang["langaccount"]}
            name="account"
            rules={[{ required: true }]}
          >
            <Input disabled={true} />
          </Form.Item>
          <Form.Item
            label={lang["langprivilege"]}
            name="privilege"
            rules={[{ required: true }]}
          >
            <Select>
              {privateOption.map(({ cnlabel, label, value, sort }) => (
                <Option key={sort} value={value}>
                  {langCur === "en" ? label : cnlabel}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    );
  })
);

const User: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  const {
    languageStore: { lang, langCur },
    userStore: { getAllUser, allUser, allUserLoading },
    dictionaryStore: { getDictValuesByKey },
  } = store;

  const [userTypeList, setUserTypeList] = useState<ITDictValue[]>([]);

  const [editPermData, setEditPermData] = useState<ITUserInfo | null>(null);

  const [editPwdData, setEditPwdData] = useState<ITUserInfo | null>(null);

  useEffect(() => {
    const getData = async () => {
      await getAllUser();
    };
    getData();
    const userTypes: ITDictValue[] = getDictValuesByKey("userType");
    setUserTypeList(userTypes);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const changePermission = (record: ITUserInfo) => {
    setEditPermData(record);
  };

  const clearPermissionData = () => setEditPermData(null);

  const changePwd = (record: ITUserInfo) => {
    setEditPwdData(record);
  };

  const clearPwdData = () => setEditPwdData(null);

  const columns: ITColumns[] = [
    {
      title: lang["langaccount"],
      dataIndex: "account",
      key: "account",
    },
    {
      title: lang["langprivilege"],
      dataIndex: "privilege",
      key: "privilege",
      render: (txt: string) => {
        let privilegeStr = "";
        userTypeList.some((item: ITDictValue) => {
          const { label, cnlabel, value } = item;
          privilegeStr = label;
          if (txt === value) {
            privilegeStr = label;
            if (langCur === "zhcn") {
              privilegeStr = cnlabel;
            }
            return true;
          }
          return false;
        });
        return privilegeStr;
      },
    },
    {
      title: lang["langedit"],
      dataIndex: "edit",
      key: "edit",
      width: 110,
      align: "center",
      render: (txt: string, record: ITUserInfo) => {
        return (
          <Space>
            <Tooltip title={lang["langchangepermi"]}>
              <Button
                type="link"
                icon={<UserSwitchOutlined />}
                onClick={() => {
                  changePermission(record);
                }}
              />
            </Tooltip>
            <Tooltip title={lang["langchangepwd"]}>
              <Button
                type="link"
                icon={<KeyOutlined />}
                onClick={() => {
                  changePwd(record);
                }}
              />
            </Tooltip>
          </Space>
        );
      },
    },
  ];

  return (
    <>
      <Table
        dataSource={allUser}
        columns={columns}
        bordered
        loading={allUserLoading}
      />

      <PermissionModal data={editPermData} close={clearPermissionData} />

      <PwdModal data={editPwdData} close={clearPwdData} />
    </>
  );
};

export default inject("store")(observer(User));
